import { getToken } from '../utils/token.js'
import store from '../store/index.js'
import { Notify, Dialog } from 'vant'

const whiteList = ['/login', '/registry'] // 无需token的路由名称

export function registryRouterHook(router) {
  router.beforeEach(async(to, from, next) => {
    const token = getToken()
    if (token) {
      if (to.path === '/login') {
        // if is logged in, redirect to the home page
        next({ path: '/' })
      } else {
        const hasGetUserInfo = store.getters.userInfo.id
        if (hasGetUserInfo) {
          next()
        } else {
          try {
            // get user info
            await store.dispatch('user/getInfo')
            next()
          } catch (error) {
            // remove token and go to login page to re-login
            await store.dispatch('user/resetToken')
            await Dialog.alert({
              message: error.message || '登录认证失效，请重新登录'
            })
            next(`/login?redirect=${to.path}`)
          }
        }
      }
    } else {
      if (whiteList.includes(to.path)) {
        // in the free login whitelist, go directly
        next()
      } else {
        // await Dialog.alert({
        //   message: '登录认证失效，请重新登录'
        // })
        // other pages that do not have permission to access are redirected to the login page.
        next(`/login?redirect=${to.path}`)
      }
    }
  })
}
